/*
 * 2011-8-22 o≧﹏≦o Powered by EXvision
 */

package org.ace.endingCode;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.handler.codec.MessageToByteEncoder;

import AceCode.ByteArray;

/**
 * 抗粘包编码器[4-length][bytes]<br>
 * 
 * @author EXvision
 * @since 2011-8-22
 */
public class LengthFieldEncoder extends MessageToByteEncoder<Object>
{
//	private static final int lengthFieldLength = 4;

	@Override
	protected void encode(io.netty.channel.ChannelHandlerContext ctx,
			Object msg, ByteBuf out) throws Exception {
		ByteBuf body = (ByteBuf) msg;
		
	//	ByteBuf header = ByteBufUtil.threadLocalDirectBuffer();

		int length = body.readableBytes();
		ByteArray arr=new ByteArray();
		arr.WriteInt(length);
		arr.WriteBytes(body.readBytes(length).array());
		out.writeBytes(arr.getBuffer());
		body.resetReaderIndex();
		//out=header;
		
	}
}
